package com.wisnews.service.sec.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wisnews.mapper.sr.NewsMapper;
import com.wisnews.pojo.sr.entity.News;
import com.wisnews.pojo.sr.vo.NewsStatistics;
import com.wisnews.service.sec.INewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yuyd
 * @since 2020-12-25
 */
@Service
@Slf4j
public class NewsServiceImpl extends ServiceImpl<NewsMapper, News> implements INewsService {
    @Autowired
    private NewsMapper newsMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /** 
     * @description: 第一次访问存入redis，页面条数，或数据条数变化时。发生更新()。爬虫结束后需要手动更新缓存
     * @param:
     * @return:
     * @author yuyd
     * @date: 2021/5/17 11:40
     */
    @Cacheable(cacheNames = "news",key = "#toPage.current+'_'+#toPage.size")
    @Override
    public IPage<News> getNewsInfo4Page(News req, IPage toPage) {

        LambdaQueryWrapper<News> lambdaQueryWrapper = Wrappers.lambdaQuery();
        //时间降序排列
        lambdaQueryWrapper.orderByDesc(News::getNewsAnnounceTime);
        lambdaQueryWrapper.like(StringUtils.isNotBlank(req.getNewsTitle()),News::getNewsTitle,req.getNewsTitle())
                .like(StringUtils.isNotBlank(req.getNewsType()),News::getNewsType,req.getNewsType())
                .like(StringUtils.isNotBlank(req.getNewsMedia()),News::getNewsMedia,req.getNewsMedia())
                .like(StringUtils.isNotBlank(req.getNewsAnnounceTime()),News::getNewsAnnounceTime,req.getNewsAnnounceTime())
                .eq(StringUtils.isNotBlank(req.getNewsState()),News::getNewsState,req.getNewsState());

        IPage<News> page = newsMapper.getNewsInfo4Page(toPage,lambdaQueryWrapper);
        return page;
    }

    @Override
    public List<String> getAllPageUrl() throws Exception{

        Object allPageUrl = redisTemplate.opsForValue().get("allPageUrl");
        if (ObjectUtils.isNotNull(allPageUrl) && allPageUrl instanceof List){
            log.info("==>从redis获取到页面url信息！");
            return (List<String>) allPageUrl;
        }
        //缓存里面没有
        log.info("==>redis中没有数据，读取数据库存入缓存！");

        List<String> urls = newsMapper.getAllPageUrl();

        //25分钟后超时
        redisTemplate.opsForValue().set("allPageUrl",urls,25, TimeUnit.MINUTES);

        return urls;
    }

    @Override
    public void bathForbiddeneNews(List<String> ids) {
         newsMapper.bathUpdateState(ids,"1");
    }

    @Override
    public void enableNews(List<String> ids) {
        newsMapper.bathUpdateState(ids,"0");
    }

    @Override
    public List<NewsStatistics> getNewsCountInfo() {
        return newsMapper.getNewsCountInfo();
    }

    /**
     * @description: 通过操作员ID，分页参数获取新闻列表
     * @param: ipage operatorId
     * @return: ipage
     * @author yuyd
     * @date: 2021/5/2 22:29
     */
    @Override
    public IPage<News> getNewsListByOperatorId(IPage toPage, String operatorId) {
        IPage<News> list = newsMapper.getNewsListForUserId(toPage,operatorId);
        return list;
    }


    @Cacheable(cacheNames = "oneNews",key = "#id")
    @Override
    public News getById(Serializable id) {
        return super.getById(id);
    }

    /**
     * @description: 批量删除覆盖
     * @param:
     * @return:
     * @author yuyd
     * @date: 2021/5/18 10:54
     */
    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        boolean b = super.removeByIds(idList);
        if (idList.size() == 1) {
            //只有一条，删除数据库后删除缓存
            Object[] key = idList.toArray();
            redisTemplate.delete("oneNews::"+key[0]);
        }
        return b;
    }
}
